package com.cleverest.cleverestdiary.validation;

import com.cleverest.cleverestdiary.anno.State;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Pattern;

public class ImageValidation implements ConstraintValidator<State, String>/*给哪个数据校验规则，校验的数据类型*/ {
    /**
     * 提供校验规则
     *
     * @param value   object to validate，将来要校验的数据
     * @param context context in which the constraint is evaluated
     * @return 如果返回false则校验不通过，返回true则通过
     */

    private static final String IMAGE_EXTENSION_REGEX = ".(jpg|jpeg|png|gif|bmp)$";
    private static final Pattern IMAGE_EXTENSION_PATTERN = Pattern.compile(IMAGE_EXTENSION_REGEX, Pattern.CASE_INSENSITIVE);

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.isEmpty()) {
            return false;
        }
        try {
            // 尝试创建 URL 对象，若为无效 URL 会抛出异常
            new java.net.URL(value);
            // 判断 URL 结尾是否为图片格式后缀名
            return IMAGE_EXTENSION_PATTERN.matcher(value).find();
        } catch (java.net.MalformedURLException e) {
            return false;
        }
    }
}
